<template>
  <div class="reset-password-container">
    <!-- 头部 -->
    <div class="header d-flex align-items-center">
      <router-link to="/" class="back-button me-3">
        <i class="bi bi-arrow-left"></i>
      </router-link>
      <h5 class="mb-0">找回密码</h5>
    </div>
    <form @submit.prevent="handleResetPassword" class="reset-form" aria-label="找回密码表单">
      <div class="reset-form">
        <div class="form-group mb-3">
          <div class="input-group">
            <span class="input-group-text">
              <i class="bi bi-phone"></i>
            </span>
            <input
                type="text"
                class="form-control"
                v-model="resetForm.phone"
                placeholder="请输入手机号"
                id="phone"
                required
                :class="{ 'is-invalid': phoneError }"
                @input="validatePhone"
            >
            <div v-if="phoneError" class="invalid-feedback">
              {{ phoneErrorMessage }}
            </div>
          </div>
        </div>

        <div class="form-group mb-4">
          <div class="input-group">
            <span class="input-group-text">
              <i class="bi bi-lock"></i>
            </span>
            <input
                type="text"
                class="form-control"
                v-model="resetForm.verificationCode"
                placeholder="请输入短信验证码"
                id="verificationCode"
                required
                :class="{ 'is-invalid': codeError }"
                @input="validateCode"
            >
            <button
                class="btn btn-outline-secondary"
                type="button"
                @click="sendVerificationCode"
                :disabled="sendingCode || sentCode || countdown > 0"
            >
              {{ countdown > 0 ? `${countdown} 秒后重试` : (sendingCode ? '发送中...' : (sentCode ? '已发送' : '发送验证码')) }}
            </button>
            <div v-if="codeError" class="invalid-feedback">
              {{ codeErrorMessage }}
            </div>
          </div>
        </div>

        <div class="form-group mb-4">
          <div class="input-group">
            <span class="input-group-text">
              <i class="bi bi-lock"></i>
            </span>
            <input
                type="password"
                class="form-control"
                v-model="resetForm.newPassword"
                placeholder="请输入新密码"
                id="newPassword"
                required
                :class="{ 'is-invalid': passwordError }"
                @input="validatePassword"
            >
            <div v-if="passwordError" class="invalid-feedback">
              {{ passwordErrorMessage }}
            </div>
          </div>
        </div>

        <div class="form-group mb-4">
          <div class="input-group">
            <span class="input-group-text">
              <i class="bi bi-lock"></i>
            </span>
            <input
                type="password"
                class="form-control"
                v-model="resetForm.confirmPassword"
                placeholder="请确认新密码"
                id="confirmPassword"
                required
                :class="{ 'is-invalid': confirmPasswordError }"
                @input="validateConfirmPassword"
            >
            <div v-if="confirmPasswordError" class="invalid-feedback">
              {{ confirmPasswordErrorMessage }}
            </div>
          </div>
        </div>

        <button
            class="btn btn-primary w-100 mb-3"
            :disabled="!isFormValid"
        >
          重置密码
        </button>
        <div class="text-center mb-4">
          <div v-if="errorMessage" class="alert alert-danger mb-3">
            {{ errorMessage }}
          </div>
        </div>
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import http from '../../router/http'
import router from "@/router/index";

// 找回密码表单数据
const resetForm = ref({
  phone: '',
  verificationCode: '',
  newPassword: '',
  confirmPassword: '',
  sendType: 2
})

// 错误信息
const errorMessage = ref('')
const phoneError = ref(false)
const phoneErrorMessage = ref('')
const codeError = ref(false)
const codeErrorMessage = ref('')
const passwordError = ref(false)
const passwordErrorMessage = ref('')
const confirmPasswordError = ref(false)
const confirmPasswordErrorMessage = ref('')

// 验证码相关状态
const sendingCode = ref(false)
const sentCode = ref(false)

// 倒计时
const countdown = ref(0)

// 手机号校验
const validatePhone = () => {
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!resetForm.value.phone) {
    phoneError.value = true
    phoneErrorMessage.value = '手机号不能为空'
  } else if (!phoneRegex.test(resetForm.value.phone)) {
    phoneError.value = true
    phoneErrorMessage.value = '手机号格式不正确'
  } else {
    phoneError.value = false
    phoneErrorMessage.value = ''
  }
}

// 验证码校验
const validateCode = () => {
  if (!resetForm.value.verificationCode) {
    codeError.value = true
    codeErrorMessage.value = '验证码不能为空'
  } else {
    codeError.value = false
    codeErrorMessage.value = ''
  }
}

// 新密码校验
const validatePassword = () => {
  if (!resetForm.value.newPassword) {
    passwordError.value = true
    passwordErrorMessage.value = '新密码不能为空'
  } else if (resetForm.value.newPassword.length < 6) {
    passwordError.value = true
    passwordErrorMessage.value = '新密码长度不能小于6位'
  } else {
    passwordError.value = false
    passwordErrorMessage.value = ''
  }
}

// 确认密码校验
const validateConfirmPassword = () => {
  if (!resetForm.value.confirmPassword) {
    confirmPasswordError.value = true
    confirmPasswordErrorMessage.value = '确认密码不能为空'
  } else if (resetForm.value.confirmPassword !== resetForm.value.newPassword) {
    confirmPasswordError.value = true
    confirmPasswordErrorMessage.value = '两次输入的密码不一致'
  } else {
    confirmPasswordError.value = false
    confirmPasswordErrorMessage.value = ''
  }
}

// 发送验证码
const sendVerificationCode = async () => {
  validatePhone()
  if (phoneError.value) return

  sendingCode.value = true
  try {
    const requestData = {
      phone: resetForm.value.phone,
      sendType: 2
    }
    const response = await http.post('/student/user/sendSmsCode', requestData);
    if (response.status === 200) {
      sentCode.value = true
      errorMessage.value = ''
      // 开始倒计时
      countdown.value = 60
      const timer = setInterval(() => {
        if (countdown.value > 0) {
          countdown.value--
        } else {
          clearInterval(timer)
          sentCode.value = false
        }
      }, 1000)
    } else {
      errorMessage.value = response.data.message || '发送验证码失败，请稍后重试'
    }
  } catch (error) {
    console.error(error)
    errorMessage.value = '网络错误，请稍后重试'
  } finally {
    sendingCode.value = false
  }
}

// 处理重置密码
const handleResetPassword = async () => {
  errorMessage.value = ''

  validatePhone()
  validateCode()
  validatePassword()
  validateConfirmPassword()

  if (phoneError.value || codeError.value || passwordError.value || confirmPasswordError.value) {
    return
  }

  try {
    const response = await http.post('/student/user/register/resetPassword', resetForm.value)
    if (response.status === 200 && response.data.code === 1) {
      alert('密码重置成功，请重新登录')
      errorMessage.value = '密码重置成功，请重新登录'
      router.push('/login')
    } else {
      errorMessage.value = response.data.message || '密码重置失败，请稍后重试'
    }
  } catch (error) {
    console.error(error)
    errorMessage.value = '网络错误，请稍后重试'
  }
}

// 表单是否有效
const isFormValid = computed(() => {
  return !phoneError.value && !codeError.value && !passwordError.value && !confirmPasswordError.value
})
</script>

<style scoped>
.reset-password-container {
  background-color: #f0f9f9;
  min-height: 100vh;
}

.header {
  background: linear-gradient(135deg, #00b8a9, #00a19a);
  color: white;
  padding: 15px;
  position: relative;
}

.reset-form {
  background: white;
  margin: 20px 15px;
  padding: 20px;
  border-radius: 15px;
}
.back-button {
  color: white;
  text-decoration: none;
  font-size: 1.2rem;
}

.input-group-text {
  background-color: white;
  border-right: none;
}

.form-control {
  border-left: none;
}

.form-control:focus {
  box-shadow: none;
  border-color: #ced4da;
}

.btn-primary {
  background: #40e0d0;
  border: none;
  padding: 12px;
  border-radius: 8px;
}

.btn-primary:hover {
  background: #3bcdc0;
}

a {
  color: #40e0d0;
}

a:hover {
  color: #3bcdc0;
}
</style>